using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.H;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return;

namespace RBAC.Write.Api.Controllers.ERP
{
    public class DeleteDtos
    {
        /// <summary>
        /// 用户id 
        /// </summary>
        public long Id { get; set; }
    }

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SalesManagementController : ControllerBase
    {
        private readonly IMediator _mediator;

        public SalesManagementController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 新增客户
        /// </summary>
        /// <param name="request">客户实体</param>
        /// <returns>新客户ID</returns>
        [HttpPost("AddCustomer")]
        public async Task<APIResult<int>> AddCustomer([FromBody] AddCustomerCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 修改客户（整体更新）
        /// </summary>
        /// <param name="id">客户Id（路由）</param>
        /// <param name="request">包含要更新的客户实体</param>
        /// <returns>影响行数</returns>
        [HttpPut("Customer/{id}")]
        public async Task<APIResult<int>> UpdateCustomer([FromRoute] int id, [FromBody] UpdateCustomerCommands request)
        {
            if (request?.customer != null)
            {
                request.customer.Id = id; // 以路由Id为准
            }
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 修改客户状态
        /// </summary>
        /// <param name="request">客户Id与目标状态</param>
        /// <returns>影响行数</returns>
        [HttpPost("UpdateCustomerStatus")]
        public async Task<APIResult<int>> UpdateCustomerStatus([FromBody] UpdateStatusCustomerCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 删除客户（软删除）
        /// </summary>
        /// <param name="id">要删除的客户Id</param>
        /// <returns>影响行数</returns>
        [HttpDelete("Customer/{id}")]
        public async Task<APIResult<int>> DeleteCustomer([FromRoute] int id)
        {
            var cmd = new DeleteCustomerCommands { CustomerId = id };
            return await _mediator.Send(cmd);
        }



        #region 销售订单

        /// <summary>
        /// 新增销售订单
        /// </summary>
        /// <param name="request">新增销售订单请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>新增结果</returns>
        [HttpPost]
        public Task<APIResult<long>> AddSalesOrder([FromBody] AddSalesOrderCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }


        /// <summary>
        /// 编辑销售订单
        /// </summary>
        /// <param name="request">编辑销售订单请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>编辑结果</returns>
        [HttpPost]
        public Task<APIResult<bool>> UpdateSalesOrder([FromBody] UpdateSalesOrderCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除销售订单 
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        [HttpPost]
        public Task<APIResult<bool>> DeleteSalesOrder([FromBody] DeleteDtos dto, CancellationToken cancellationToken)
        {
            var command = new DeleteSalesOrderCommand { Id = dto.Id };
            return _mediator.Send(command, cancellationToken);
        }

        /// <summary>
        /// 审批或反审销售订单
        /// </summary>
        /// <param name="request">审批或反审请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        [HttpPost]
        public Task<APIResult<bool>> AppOrUnappSalesOrder([FromBody] AppOrUnappSalesOrderCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 导出销售订单
        /// </summary>
        /// <param name="request">导出请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>Excel文件</returns>
        [HttpGet]
        public async Task<IActionResult> ExportSalesOrder([FromQuery] ExportSalesOrderCommand request, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(request, cancellationToken);

            if (result.Code != APIEnums.Success)
            {
                return BadRequest(result);
            }

            return File(
                result.Data,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                $"销售订单导出_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
            );
        }

        /// <summary>
        /// 导出退货通知单
        /// </summary>
        /// <param name="request">导出请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>Excel文件</returns>
        [HttpGet("ExportReturnNotice")]
        public async Task<IActionResult> ExportReturnNotice([FromQuery] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return.ExportReturnNoticeCommand request, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(request, cancellationToken);

            if (result.Code != APIEnums.Success)
            {
                return BadRequest(result);
            }

            var exportType = request.ExportType == 1 ? "退货通知单" : "退货明细";
            return File(
                result.Data,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                $"{exportType}导出_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
            );
        }

        #endregion
        /// <summary>
        /// 创建发货单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> CreateDelivery_notice(CreateDelivery_noticeCommand request)
        {
            return await _mediator.Send(request);
        }

        #region 退货通知单

        /// <summary>
        /// 创建退货通知单
        /// </summary>
        /// <param name="request">退货通知单信息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public Task<APIResult<int>> CreateReturnNotice([FromBody] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return.CreateReturnNoticeCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除退货通知单
        /// </summary>
        /// <param name="dto">退货通知单ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        [HttpPost("DeleteReturnNotice")]
        public Task<APIResult<int>> DeleteReturnNotice([FromBody] DeleteDtos dto, CancellationToken cancellationToken)
        {
            var command = new RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return.DeleteReturnNoticeCommand
            {
                Id = dto.Id
            };
            return _mediator.Send(command, cancellationToken);
        }

        /// <summary>
        /// 审核/反审核/退回 退货通知单
        /// </summary>
        /// <param name="request">审核请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        [HttpPost("ApproveOrReturnReturnNotice")]
        public Task<APIResult<bool>> ApproveOrReturnReturnNotice([FromBody] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return.ApproveOrReturnReturnNoticeCommand request, CancellationToken cancellationToken)
        {
            // 从Claims中获取当前用户ID
            var userId = long.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value ?? "0");
            request.AuditUserId = userId;
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 更新退货通知单
        /// </summary>
        /// <param name="command">更新命令</param>
        /// <returns>更新结果</returns>
        [HttpPut("UpdateReturnNotice")]
        public async Task<APIResult<int>> UpdateReturnNotice([FromBody] UpdateReturnNoticeCommand command)
        {
            return await _mediator.Send(command);
        }

        #endregion

        #region 开票通知单

        /// <summary>
        /// 创建开票通知单
        /// </summary>
        /// <param name="request">开票通知单信息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        [HttpPost("CreateBillingNotice/CreateBillingNotice")]
        public Task<APIResult<int>> CreateBillingNotice([FromBody] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing.CreateBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除开票通知单（逻辑删除）
        /// </summary>
        /// <param name="dto">开票通知单ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        [HttpPost("DeleteBillingNotice")]
        public Task<APIResult<int>> DeleteBillingNotice([FromBody] DeleteDtos dto, CancellationToken cancellationToken)
        {
            var command = new RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing.DeleteBillingNoticeCommand
            {
                Id = dto.Id
            };
            return _mediator.Send(command, cancellationToken);
        }

        /// <summary>
        /// 更新开票通知单
        /// </summary>
        /// <param name="request">开票通知单更新信息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        [HttpPost("UpdateBillingNotice")]
        public Task<APIResult<int>> UpdateBillingNotice([FromBody] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing.UpdateBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 审核开票通知单
        /// </summary>
        /// <param name="request">审核请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>审核结果</returns>
        [HttpPost("AuditBillingNotice")]
        public Task<APIResult<bool>> AuditBillingNotice([FromBody] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing.AuditBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 反审核开票通知单
        /// </summary>
        /// <param name="request">反审核请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反审核结果</returns>
        [HttpPost("UnAuditBillingNotice")]
        public Task<APIResult<bool>> UnAuditBillingNotice([FromBody] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing.UnAuditBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 导出开票通知单
        /// </summary>
        /// <param name="request">导出请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>Excel文件</returns>
        [HttpGet("ExportBillingNotice")]
        public async Task<IActionResult> ExportBillingNotice([FromQuery] RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing.ExportBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(request, cancellationToken);

            if (result.Code != APIEnums.Success)
            {
                return BadRequest(result);
            }

            var exportType = request.ExportType == 1 ? "开票通知单" : "开票明细";
            return File(
                result.Data,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                $"{exportType}导出_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
            );
        }

        #endregion
    }
}
